package com.xkdx.caipiao.cost;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.xkdx.caipiao.R;
import com.xkdx.caipiao.RechargeActivity;
import com.xkdx.caipiao.ThreadActivity;
import com.xkdx.caipiao.module.network.AbsModule;
import com.xkdx.caipiao.my.PhoneDetailActivity;
import com.xkdx.caipiao.presistence.cost.CostAction;
import com.xkdx.caipiao.presistence.cost.CostModule;
import com.xkdx.caipiao.presistence.cost.CostPresistence;
import com.xkdx.caipiao.presistence.costlist.CostListAction;
import com.xkdx.caipiao.presistence.costlist.CostListInfo;
import com.xkdx.caipiao.presistence.costlist.CostListModule;
import com.xkdx.caipiao.presistence.costlist.CostListPresistence;
import com.xkdx.caipiao.statics.IConstants;
import com.xkdx.caipiao.util.IsMobileNum;
import com.xkdx.caipiao.util.Md5Utils;
import com.xkdx.guangguang.LoginActivity;
import com.xkdx.guangguang.util.PhoneUtil;

public class CostRechargeActivty extends ThreadActivity {
    //	LoginInfo info;
    private CostAction action;
    private CostModule module;
    private CostPresistence presistence;

    private CostListAction listaction;
    private CostListModule listmodule;
    private CostListPresistence listpresistence;
    private List<CostListInfo> list;
    private String devicetype = "2";
    private String proid;
    boolean isVisiable = false;
    private EditText et_phone_num;
    private LinearLayout see_item_number;
    private Button sure_pay;
    TextView tv_money, cost_money, phone_info;
    ListView listView;
    ImageView arrow;
    MyAdapter adapter;
    private String numb;
    private String code = "1";
    private int count = 0;
    private PhoneTask phoneTask;
//	public static LoginInfo loginInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cost_caipiao);
        init();
        startThread();
        list = new ArrayList<CostListInfo>();

    }

    private void init() {
        et_phone_num = (EditText) findViewById(R.id.et_phone_num);
        tv_money = (TextView) findViewById(R.id.tv_money);
        cost_money = (TextView) findViewById(R.id.cost_money);
        phone_info = (TextView) findViewById(R.id.cost_phone_type);
        /*
         * cmcc =
		 * "^1(34[0-8]|(3[5-9]|47|5[0-2]|57[124]|5[89]|8[2378])\\d)\\d{7}$";
		 * cdma = "^1(3[0-2]|45|5[56]|8[56])\\d{8}$"; wcdma =
		 * "^1(33|53|8[09])\\d{8}$";
		 */
        sure_pay = (Button) findViewById(R.id.sure_pay);
        listView = (ListView) findViewById(R.id.lv_list);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                CostListInfo info = (CostListInfo) adapter.getItem(arg2);
                float mon1 = Float.valueOf(info.getValue()) / 100;
                DecimalFormat df = new DecimalFormat("#0.00");
                tv_money.setText(info.getTitle());
                cost_money.setText("售价 " + "￥" + String.valueOf(df.format(mon1)));
                arrow.setImageResource(R.drawable.down_arrow_more_caipiao);
                listView.setVisibility(View.GONE);
                proid = info.getId();
                // 如果点击的这个是红的将其改变为白色的
				/*if (listmodule.list.get(arg2).isChecked) {
					listmodule.list.get(arg2).isChecked = false;
				} else {// 如果点击的是白的，先将所有变白
					for (CostListInfo hb : listmodule.list) {
						hb.isChecked = false;
					}
					listmodule.list.get(arg2).isChecked = true;
				}
				adapter.notifyDataSetChanged();*/

            }
        });
        sure_pay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                numb = et_phone_num.getText().toString();
                boolean isnum = IsMobileNum.isMobileNum(numb);
//                String info = IsMobileNum.isMobileInfo(numb);
                if ("".equals(numb)) {
                    Toast.makeText(CostRechargeActivty.this, "手机号码不能为空", 1)
                            .show();
                    return;
                }
                if (isnum == false) {
                    Toast.makeText(CostRechargeActivty.this, "请输入正确的手机号码", 1)
                            .show();
                    return;
                }
//                if ("联通".equals(info)) {
//                    Toast.makeText(CostRechargeActivty.this, "只支持移动和电信充值", 1)
//                            .show();
//                    return;
//                }
                if ("".equals(proid)) {
                    Toast.makeText(CostRechargeActivty.this, "请选择要充值的金额", 1)
                            .show();
                }
//				loginInfo = getLoginInfo();
                if (usrSP != null
                        && !(TextUtils.isEmpty(usrSP.getLogintoken()))) {
                    if (numb != null && proid != null) {
                        startThreadCost();
                    }
                } else {
                    Intent inten3 = new Intent(CostRechargeActivty.this, LoginActivity.class);
                    startActivity(inten3);
                }


            }
        });
        arrow = (ImageView) findViewById(R.id.im_arrow);
        see_item_number = (LinearLayout) findViewById(R.id.see_item_number);
        see_item_number.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (isVisiable) {

                    isVisiable = false;
                    arrow.setImageResource(R.drawable.down_arrow_more_caipiao);
                    listView.setVisibility(View.GONE);
                } else {
                    isVisiable = true;
                    arrow.setImageResource(R.drawable.up_arrow_more_caipiao);
                    listView.setVisibility(View.VISIBLE);
                }

            }

        });

        et_phone_num.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {

            }

            @Override
            public void afterTextChanged(Editable edt) {
                String phone = edt.toString();
                //判断是手机，则开始查询信息
                if (IsMobileNum.isMobileNum(phone)) {
                    count++;
                    phoneTask = new PhoneTask(count, phone);
                    phoneTask.execute();
                }
            }
        });
    }

    private void setPhoneInfo(String info) {
        phone_info.setText(info);
    }

    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void showOnPost(HashMap<String, AbsModule> result) {
        dataLoadDialog.dismiss();
        if (result.containsKey("0")) {
            adapter = new MyAdapter(listmodule.list);
            listView.setAdapter(adapter);

        }
        if (isVisiable == true) {
            code = module.code;
            if ("0000".equals(code)) {
                Toast.makeText(CostRechargeActivty.this, "提交成功", 1).show();
                Intent inte = new Intent(this, PhoneDetailActivity.class);
                startActivity(inte);
            } else if ("5004".equals(code)) {
                Toast.makeText(CostRechargeActivty.this, "登录失效", 1).show();
                setLogin();
            } else if ("1014".equals(code)) {
                Toast.makeText(CostRechargeActivty.this, "金额不足，请先充值", 1).show();
                Intent intent = new Intent(this, RechargeActivity.class);
                startActivity(intent);
            }
        }

    }

    class PhoneTask extends AsyncTask<String, Integer, String> {
        int num;
        String phone;

        public PhoneTask(int num, String phone) {
            this.num = num;
            this.phone = phone;
        }

        @Override
        protected String doInBackground(String... arg0) {
            String result = PhoneUtil.getBasicInfo(phone);
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            Log.i("phone info is===>", result);
            String arr[] = result.split(" ");
            String lastPart = arr[arr.length - 1];
            if (lastPart.indexOf("联通") > 0) {
                int end = lastPart.indexOf("联通") + 2;
                result = lastPart.substring(0, end);
            } else if (lastPart.indexOf("移动") > 0) {
                int end = lastPart.indexOf("移动") + 2;
                result = lastPart.substring(0, end);
            } else if (lastPart.indexOf("电信") > 0) {
                int end = lastPart.indexOf("电信") + 2;
                result = lastPart.substring(0, end);
            }
            Log.i("array info is===>", lastPart);
            if (num == count) {
                setPhoneInfo(result);
            }
        }

    }

    class Holder {
        TextView tv_ye;

    }

    class MyAdapter extends BaseAdapter {

        private List<CostListInfo> list2;

        public MyAdapter(List<CostListInfo> list2) {
            this.list2 = list2;
        }

        public int getCount() {
            return list2.size();
        }

        @Override
        public Object getItem(int position) {
            return list2.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            Holder holder = null;
            if (convertView == null) {
                holder = new Holder();
                convertView = LayoutInflater.from(getApplicationContext())
                        .inflate(R.layout.phone_number_caipiao, null);

                holder.tv_ye = (TextView) convertView.findViewById(R.id.tv_ye);

                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            CostListInfo tmep = list2.get(position);
            float mon1 = Float.valueOf(list2.get(position).getValue()) / 100;
            DecimalFormat df = new DecimalFormat("#0.00");
            String money = df.format(mon1);
            holder.tv_ye.setText(tmep.getTitle());
            return convertView;
        }

    }

    public void startThread() {
        if (!(dataLoadDialog.isShowing())) {
            dataLoadDialog.show();
            dataLoadDialog.setContentView(R.layout.progressbar_caipiao);

            listaction = new CostListAction();
            listmodule = new CostListModule();
            listpresistence = new CostListPresistence(this);
            listpresistence.setActitons(listaction);
            listpresistence.setModule(listmodule);
            listpresistence.execute();

        }
    }

    public void startThreadCost() {
        if (!(dataLoadDialog.isShowing())) {
            dataLoadDialog.show();
            dataLoadDialog.setContentView(R.layout.progressbar_caipiao);
            isVisiable = true;
//			LoginInfo info = getLoginInfo();
            String md5 = usrSP.getId() + usrSP.getLogintoken() + IConstants.key;
            String signcode = Md5Utils.md5(md5);
            action = new CostAction(usrSP.getId(), usrSP.getLogintoken(),
                    devicetype, proid, numb, signcode);
            module = new CostModule();
            presistence = new CostPresistence(this);
            presistence.setActitons(action);
            presistence.setModule(module);
            presistence.execute();

        }
    }

}
